/*
** pickfile.c
**
** Pictor, Version 1.51, Copyright (c) 1992-94 SoftCircuits
** Redistributed by permission.
*/

#include <dos.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include "pictor.h"

struct find_t fileinfo;

/* Note: a pointer to this structure is passed as a pointer to a */
/* string to listbox(), so name[] must always be the first member */
struct filename {
	char name[14];
	struct filename *next;
};

static struct filename *head,*new,*curr;
static struct filename **filearray;


/*
** Frees pickfile() memory structures.
*/
static void free_filemem(void)
{
	struct filename *ptr,*next;

	for(ptr = head;ptr != NULL;ptr = next) {
		next = ptr->next;
		free(ptr);
	}
	if(filearray != NULL) free(filearray);

} /* free_filemem */

/*
** Compare routine for qsort().
*/
static int compare(const void *elem1,const void *elem2)
{
	return(strcmp(*(char **)elem1,*(char **)elem2));

} /* compare */

/*
** Uses listbox to select from the files matching filespec. Returns
** a pointer to the selected filename. Returns NULL if user pressed
** Escape, not enough memory, or no files matching filespec. Yo can
** use escpressed() to determine which occured.
*/
char *pickfile(char *filespec,char *title,COLORSTRUCT *colors)
{
	int i,numfiles = 0,selection = 0;
	static char buffer[13];

	head = NULL;
	filearray = NULL;

	/* build linked list of files in current directory */
	#ifdef EXT_PICKFILE
		if(!_dos_findfirst(filespec,_A_SUBDIR,&fileinfo)) {
	#else
		if(!_dos_findfirst(filespec,_A_NORMAL,&fileinfo)) {
	#endif
		do {
			new = (struct filename *)malloc(sizeof(struct filename));
			if(new == NULL) {
				free_filemem();
				return(NULL);
			}

			if(head == NULL)
				head = new;
			else
				curr->next = new;
			curr = new;
			curr->next = NULL;

			strcpy(curr->name,fileinfo.name);
			numfiles++;

		} while(!_dos_findnext(&fileinfo));
	}
	if(numfiles == 0) {
		messagebox("No files found",title,MB_OK,colors);
		return(NULL);
	}

	/* build array of pointers */
	filearray = (struct filename **)malloc(sizeof(struct filename)*numfiles);
	if(filearray == NULL) {
		free_filemem();
		return(NULL);
	}
	for(i = 0,curr = head;i < numfiles;i++,curr = curr->next) {
		filearray[i] = curr;
	}

	qsort(filearray,numfiles,sizeof(struct filename *),compare);

	if(listbox((char **)filearray,numfiles,&selection,title,colors)) {
		strcpy(buffer,filearray[selection]->name);
		free_filemem();
		return(buffer);
	}
	free_filemem();
	return(NULL);

} /* pickfile */
